package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.gongpingjialoan.R;
import com.gongpingjialoan.adapter.AddressAdapter;
import com.gongpingjialoan.bean.SuggestionPlace;
import com.gongpingjialoan.widget.LoadingDialog;

import java.util.List;


public class MapActivity extends Activity implements OnMarkerClickListener, OnPoiSearchListener,
        AMapLocationListener, OnMapClickListener, OnGeocodeSearchListener {

    private static final int REQUEST_KEY = 0;

    private MapView mMapView;

    private AMap aMap;

    private PoiSearch mPoiSearch;

    private PoiSearch.Query mQuery;

    private TextView mSearchEdit;

    private LocationManagerProxy mLocationManager;

    // private MarkerOptions mMarkerOptions;

    private boolean mIsFirstLocate = true;


    private GeocodeSearch mGeoSearch;

    private LatLng mCurLatLng;

    private RegeocodeAddress mAddress;

    private Marker mMarker;

    private LoadingDialog loadingDialog;

    private ListView mSuggestionList;

    private AddressAdapter mAdapter;

    private List<SuggestionPlace> mDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        loadingDialog = new LoadingDialog(this, "定位中....");
        mMapView = (MapView) findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        setUpMap();
        mSearchEdit = (TextView) findViewById(R.id.et_search);
        findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent it = new Intent(MapActivity.this, SearchPlaceActivity.class);
                startActivityForResult(it, REQUEST_KEY);
            }
        });

        findViewById(R.id.title_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        loadingDialog.show();

        mSuggestionList = (ListView) findViewById(R.id.lv_suggestion);
        mAdapter = new AddressAdapter(MapActivity.this);
        mSuggestionList.setAdapter(mAdapter);
        mSuggestionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiItem item = mAdapter.getItem(position);
                Intent it = new Intent();
                it.putExtra("city", item.getCityName());
                it.putExtra("province", item.getProvinceName());
                it.putExtra("district", item.getDirection());
                it.putExtra("address", item.getAdName());

                it.putExtra("title", item.getTitle());
                it.putExtra("detail", item.getSnippet());
                it.putExtra("longitude", item.getLatLonPoint().getLongitude());
                it.putExtra("latitude", item.getLatLonPoint().getLatitude());

                setResult(RESULT_OK, it);
                finish();
            }
        });
    }

    public void setUpMap() {
        aMap = mMapView.getMap();
//        aMap.setOnMarkerClickListener(this);
//        aMap.setOnMapClickListener(this);
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                if (cameraPosition != null) {
                    mMarker.setPosition(cameraPosition.target);
                }
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                mCurLatLng = cameraPosition.target;
                LatLonPoint latLonPoint = new LatLonPoint(mCurLatLng.latitude, mCurLatLng.longitude);
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                mGeoSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
            }
        });
        mLocationManager = LocationManagerProxy.getInstance(this);
        // 混合定位，默认开启gps定位
        mLocationManager.setGpsEnable(true);
        mLocationManager.requestLocationData(LocationProviderProxy.AMapNetwork, 20000, 10, this);

        // mMarkerOptions = new MarkerOptions();
        // mMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_position));
        // mMarkerOptions.draggable(true);

        // 地址编码
        mGeoSearch = new GeocodeSearch(this);
        mGeoSearch.setOnGeocodeSearchListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mMapView.onPause();
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(this);
        }
        mLocationManager = null;
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(this);
            mLocationManager.destroy();
        }
        mLocationManager = null;

        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        super.onDestroy();
    }


    @Override
    public void onPoiItemDetailSearched(PoiItemDetail detail, int rCode) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        if (rCode == 0) {
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(mQuery)) {
                    // 是否同一条
                    List<PoiItem> poiItems = result.getPois();
                    // 当搜索不到poi item数据时，会返回含有搜索关键字的城市信息
                    List<SuggestionCity> suggestionCities = result.getSearchSuggestionCitys();
                    if (poiItems != null && poiItems.size() > 0) {

                        PoiItem item = poiItems.get(0);
//
                        RegeocodeQuery query = new RegeocodeQuery(item.getLatLonPoint(), 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                        mGeoSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求

                    } else if (suggestionCities != null && suggestionCities.size() > 0) {
                        Toast.makeText(MapActivity.this, "条件模糊，请重新搜索", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
            }
        } else if (rCode == 27) {
            Toast.makeText(MapActivity.this, "网络出问题啦", Toast.LENGTH_SHORT).show();
        } else if (rCode == 32) {
            Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
//        mCurLatLng = marker.getPosition();
//        LatLonPoint latLonPoint = new LatLonPoint(mCurLatLng.latitude, mCurLatLng.longitude);
//        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//        mGeoSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
        return true;
    }


    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        if (location != null) {
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            if (mIsFirstLocate) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                mMarker = aMap.addMarker(new MarkerOptions().anchor(0.7f, 0.7f).icon(
                        BitmapDescriptorFactory.fromResource(R.drawable.icon_map_location)));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 15));
                mCurLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                mIsFirstLocate = false;
                LatLonPoint latLonPoint = new LatLonPoint(ll.latitude, ll.longitude);
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                mGeoSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
            }
        }
    }

    @Override
    public void onMapClick(LatLng ll) {
        // TODO Auto-generated method stub
//        mCurLatLng = ll;
//        LatLonPoint latLonPoint = new LatLonPoint(ll.latitude, ll.longitude);
//        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);//
//        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//        mGeoSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int arg1) {

    }

    // 逆地址编码
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 0) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {

                mAddress = result.getRegeocodeAddress();
                List<PoiItem> list = mAddress.getPois();
                mAdapter.setData(mAddress.getProvince() + mAddress.getCity(), list);
                if (mAddress.getPois().size() > 0) {
                    PoiItem item = mAddress.getPois().get(0);
                    mCurLatLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint()
                            .getLongitude());
                } else {
                    Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
            }
        } else if (rCode == 27) {
            Toast.makeText(MapActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
        } else if (rCode == 32) {
            Toast.makeText(MapActivity.this, "api key有误", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MapActivity.this, "暂无搜索结果", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_KEY) {
                setResult(Activity.RESULT_OK, data);
                finish();
            }
        }

    }

}